// pages/addressList/addressList.js
import {
  getAddress,
  delAddress
} from '../../network/index.js';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    fromMe: false,
    acAddressId:"",
    addressList: []
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    const {fromPage,addressId} = options;
    if(!addressId && fromPage === "order"){
      this.toNewAddress();
    }
    this.setData({
      fromMe: fromPage === "me",
      acAddressId: addressId,
    })
  },
  //用户点击地址选中返回上一页 在订单页进来时
  bingAdress(options) {
    if(this.data.fromMe){
      return;
    }
    
    const {id} = options.currentTarget.dataset.acaddress;
    const eventChannel = this.getOpenerEventChannel();
    // 触发一个 bingAdress 让购物车页收到选中id
    eventChannel.emit('bingAdress', {data: id});
    // wx.setStorageSync("acAddress", acAddress);
    wx.navigateBack({
      delta: 1
    })
  },

  //用户编辑地址
  editAdress(event) {
    let editAdress = event.currentTarget.dataset.item;
    wx.navigateTo({
      url: `../address/address`,
      success: function(res) {
        // 通过eventChannel向被打开页面传送数据
        res.eventChannel.emit('acceptDataFromOpenerPage', { editAdress })
      }
    });
  },
  // 删除地址
  delAdress(event) {
    const that = this;
    const {
      id
    } = event.currentTarget.dataset;
    wx.showModal({
      title: '提示',
      content: '确定删除吗？',
      async success(res) {
        if (res.confirm) {
          await delAddress({id});
          that.getAddress();
        }
      }
    })
  },

  getAddress() {
    getAddress().then((result) => {
      this.setData({
        addressList: result
      })
    })
  },

  //新建地址
  toNewAddress() {
    wx.navigateTo({
      url: '../address/address'
    });
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.getAddress();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})